<template>
  <div class="detailWrap">
    <div class="flex-box">
      <div class="flex-item-box left">
        <el-card class="card" v-if="!noData">
          <div class="mainTitle">
            <p>
              <span v-html="detailData.title"></span>
              <span class="transLate" @click="handleTransLate()" v-if="!isChina"
                >译</span
              >
            </p>
            <p>
              <!-- 收藏 -->
              <el-tooltip
                :content="!collectInfo.isCollection ? '收藏' : '取消收藏'"
                placement="top"
              >
                <a
                  class="collect"
                  :class="{
                    'el-icon-star-on': collectInfo.isCollection,
                    'el-icon-star-off': !collectInfo.isCollection,
                  }"
                  @click="handleCollect"
                ></a>
              </el-tooltip>
            </p>
          </div>
          <p class="time">
            <span>{{ transTime(detailData.pubdate) }}</span>
            <span v-if="isChina">{{ detailData.source }}</span>
            <span v-if="isChina">{{ detailData.types }}</span>
          </p>
          <el-divider></el-divider>
          <div class="content" ref="content" v-html="detailData.text"></div>
          <div
            v-if="detailData.keywords && detailData.keywords.length > 0"
            class="keyWord"
          >
            <span>关键词：</span>
            <el-tag
              v-for="(i, index) in detailData.keywords"
              class="keyWord"
              :key="index"
              >{{ i }}</el-tag
            >
          </div>
          <div class="url">
            原文地址：<a :href="detailData.url" target="_blank" style="color: #03b38c;">{{
              detailData.url
            }}</a>
          </div>
          <div class="downLoad" @click="exportReport()">下载文本</div>
          <el-divider></el-divider>
          <div class="tag-box">
            <h4>相关标签</h4>
            <div class="tag-list">
              <p v-for="(item, index) in tagList" :key="index">
                <span
                  v-for="(citem, j) in item.list"
                  :key="j"
                  :class="item.class"
                  @click="toPage(citem)"
                >
                  {{ citem }}
                </span>
              </p>
              <!-- <span  :key="index" :class="item.class">{{
                item.name
              }}</span> -->
            </div>
          </div>
        </el-card>
      </div>
      <div class="flex-item-box right">
        <el-card class="card2">
          <h4>相关推荐</h4>
          <ul class="recommend-list">
            <li v-for="(item, index) in recommendList" :key="index">
              <i class="circle"></i>
              <p
                class="content"
                @click="toDetail(item)"
                v-html="item.title"
              ></p>
            </li>
          </ul>
        </el-card>
      </div>
    </div>
    <el-dialog
      title="译文对照"
      :visible.sync="showTransLate"
      width="80%"
      :before-close="handleClose"
    >
      <div v-if="!noTranslateData" class="wrap">
        <div class="left">
          <h4 class="mtitle" v-html="detailData.title"></h4>
          <div class="content" ref="content" v-html="detailData.text"></div>
        </div>
        <div class="right">
          <h4 class="mtitle">{{ dataTranslate.title }}</h4>
          <div class="content" ref="content" v-html="dataTranslate.text"></div>
        </div>
      </div>
      <div v-if="noTranslateData" class="no-data">
        <loading1 emptyText="服务异常，稍后再试" />
      </div>
    </el-dialog>
    <div v-if="noData" class="no-data">
      <loading1 emptyText="服务异常，稍后再试" />
    </div>
  </div>
</template>
<script>
import { deleteTag } from "@/utils/utils.js";
export default {
  inject: ["reload"],
  components: {},
  data() {
    return {
      id: "",
      detailData: {},
      dataTranslate: {},
      showTransLate: false,
      noTranslateData: false,
      noData: false,
      emptyText: "翻译失败，稍后再试",
      isChina: false,
      tagList: [], // 相关标签
      recommendList: [], // 相关推荐
      collectInfo: {}, // 收藏
    };
  },
  methods: {
    handleCollect() {
      let dd = this.collectInfo;
      if (dd.isCollection) {
        this.$confirm("您确定取消收藏吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          this.$delete(
            `${this.$Url.collect.collectionDelete}/${dd.collectionId}`,
            {}
          ).then((res) => {
            this.$message({
              type: "success",
              message: "取消成功！",
            });
            this.$set(this.collectInfo, "isCollection", false);
          });
        });
      } else {
        const param = {
          title: this.detailData.title,
          sourceId: this.detailData.id,
          sourceType: "NEWS",
        };
        param.title = deleteTag(param.title);
        param.userId = JSON.parse(localStorage.getItem("homeUserInfo")).id;
        this.$post(this.$Url.collect.collectionAdd, param).then((res) => {
          this.$message({
            type: "success",
            message: "收藏成功！",
          });
          this.$set(this.collectInfo, "isCollection", true);
          this.$set(this.collectInfo, "collectionId", res.data);
        });
      }
    },
    init() {
      this.id = this.$route.query.id ? this.$route.query.id : "";
      this.getData();
      this.getRecommendList();
    },
    getData() {
      this.noData = true;
      this.$post(this.$Url.industryPointOfView.getDeteilsById, {
        id: this.id,
      }).then((res) => {
        this.noData = false;
        let data = res.data || {};
        // 收藏信息
        this.collectInfo = {
          collectionId: data.collectionId,
          isCollection: data.isCollection,
        };
        // 文章信息
        let info = data && data.news_gdt;
        this.$nextTick(() => {
          this.isChina = this.isChinese(info.text);
          this.detailData = info;
          info.text = info.text.replace(
            new RegExp("<p>", "g"),
            '<p style="margin:0.07rem 0">'
          );
          // 移除无法正常展示的图片，比如img的src中没有http
          let imgReg = /<img.*?(?:>|\/>)/gi; // 匹配图片中的img标签
          let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配图片中的src
          let imgArr = info.text.match(imgReg);
          imgArr.forEach((v) => {
            let src = v.match(srcReg);
            if (src.indexOf("http") < 0) {
              info.text = info.text.replace(new RegExp(v, "g"), "");
            }
          });
          //
          info.text = info.text.replace(
            /<img/g,
            '<img style="max-width:100%;height:auto"'
          );
        });
        // 相关标签
        let listData = [];
        let fragmentation = data.fragmentation || {};
        // console.log("data", data);
        if (fragmentation["people"]) {
          // 人物
          listData.push({
            type: "people",
            class: "blue",
            list: fragmentation["people"],
          });
        }
        if (fragmentation["topic"]) {
          // 话题
          listData.push({
            type: "topic",
            class: "green",
            list: fragmentation["topic"],
          });
        }
        if (fragmentation["place"]) {
          // 地点
          listData.push({
            type: "place",
            class: "red",
            list: fragmentation["place"],
          });
        }
        if (fragmentation["organization"]) {
          // 组织
          listData.push({
            type: "organization",
            class: "orange",
            list: fragmentation["organization"],
          });
        }
        this.tagList = listData;
      });
    },
    // 相关推荐
    getRecommendList() {
      this.$post(this.$Url.industryPointOfView.opinionSuggest, {
        id: this.id,
        // id: 'FHwBHYAB_udokfof6ldd'
      }).then((res) => {
        let data = res.data;
        this.recommendList = data;
      });
    },
    // 相关推荐跳转
    toPage(item) {
      this.$router.push({
        name: "IndustryPointOfView",
        query: {
          keyword: item,
        },
      });
    },
    toDetail(item) {
      this.$router.push({
        name: "ConsultDetail",
        query: {
          id: item.id,
        },
      });
      this.reload();
    },
    exportReport() {
      if (this.downloading) {
        return;
      }
      this.downloading = true;
      this.$post(
        this.$Url.consultModule.export,
        { ids: [this.id] },
        { responseType: "arraybuffer" }
      ).then((res) => {
        this.downloading = false;
        const data = res;
        const url = window.URL.createObjectURL(
          new Blob([data], { type: "application/msword" })
        );
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", `${this.formatDateTime(new Date())}.doc`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    transTime(date) {
      return moment(date).format("YYYY-MM-DD");
    },
    // 判断是否为中文
    isChinese(str) {
      var regEx = "[\u4e00-\u9fa5]";
      let flg = false;
      if (str.match(regEx)) flg = true;
      return flg;
    },
    // 分情况处理返回值
    handleTransLate() {
      let isChinese = this.isChinese(this.detailData.title);
      this.showTransLate = true;
      this.noTranslateData = true;
      this.$post(this.$Url.consultModule.translat, {
        text:
          this.detailData.title +
          "\n" +
          this.detailData.text.replace(/\n/g, "<br/>"),
      }).then((res) => {
        if (res.status === 200) {
          this.noTranslateData = false;
          let list = res.data.translation[0].translated[0]["translation list"];
          this.dataTranslate.title = list[0][0];

          let textList = list[1];
          this.dataTranslate.text = "";
          for (let i = 0; i < textList.length; i++) {
            this.dataTranslate.text += "<p>" + textList[i] + "</p>";
          }
        }
      });
    },
    handleClose() {
      this.showTransLate = false;
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
.detailWrap {
  padding: 0;
  .flex-box {
    position: relative;
    display: flex;
    padding: 0;
    .flex-item-box {
      padding: 0;
      margin-right: 10px;
      &:last-of-type {
        margin-right: 0;
      }
      &.left {
        width: calc(100% - 3.6rem - 20px);
      }
      &.right {
        width: 3.6rem;
      }
      // &.x4 {
      //   width: calc((100% - 10px)/4);
      // }
      // &.x20 {
      //   width: calc((100% - 10px)*0.75);
      // }
    }
  }
  .card {
    padding: 0;
    height: 100%;
    .mainTitle {
      padding: 0;
      text-align: left;
      font-weight: 700;
      font-size: 22px;
      margin-top: 0.3rem;
      margin-bottom: 0.3rem;
      display: flex;
      justify-content: space-between;
    }
    .time {
      padding: 0;
      text-align: left;
      font-size: 14px;
      color: #999999;
      margin: 0.05rem 0;
      span {
        padding: 0 0.1rem;
      }
    }
    .content {
      line-height: 2;
      margin-top: 0.2rem;
      margin-bottom: 0.2rem;
      color: #2c3e50;
    }
  }
  .keyWord {
    margin-left: 0.05rem;
    font-size: 12px;
    margin: 0.1rem 0;
    span {
      margin-right: 10px;
      &:first-of-type {
        margin-right: 4px;
      }
    }
  }
  .url {
    font-size: 12px;
  }
  .downLoad {
    width: 70px;
    height: 25px;
    background: $mainColor;
    color: #ffffff;
    font-size: 12px;
    line-height: 25px;
    text-align: center;
    margin: 0.15rem 0;
    cursor: pointer;
    padding: 0;
    margin-left: 0.4rem;
  }
  .card2 {
    height: 100%;
    ::v-deep {
      padding: 0;
    }
    h4 {
      line-height: 24px;
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 400;
      color: rgba(130, 129, 129, 1);
    }
    .recommend-list {
      li {
        display: flex;
        margin-bottom: 0.1rem;
        .circle {
          width: 5px;
          height: 5px;
          margin-top: 8px;
          background-color: #9d9d9d;
        }
        .content {
          width: calc(100% - 12px);
          line-height: 1.6;
          padding-left: 10px;
          padding-right: 0;
          font-size: 14px;
          color: $mainColor;
          cursor: pointer;
        }
      }
    }
  }
  .tag-box {
    position: relative;
    padding: 0 0.4rem;
    margin-bottom: 0.2rem;
    h4 {
      line-height: 23px;
      margin-bottom: 0.15rem;
      font-size: 16px;
      font-weight: 400;
      color: #828181;
    }
    .tag-list {
      position: relative;
      padding: 0;
      p {
        display: inline-block;
        padding: 0;
        span {
          display: inline-block;
          padding: 0.08rem 0.14rem;
          margin-right: 10px;
          margin-bottom: 10px;
          border-width: 1px;
          border-style: solid;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          &:hover {
            opacity: 0.8;
          }
          &.blue {
            border-color: $mainColor;
            color: $mainColor;
            background-color: #e9f3ff;
          }
          &.green {
            border-color: #7ac756;
            color: #7ac756;
            background-color: #eef8e8;
          }
          &.red {
            border-color: #f26161;
            color: #f26161;
            background-color: #feeeee;
          }
          &.orange {
            border-color: #e29836;
            color: #e29836;
            background-color: #fdf5e9;
          }
        }
      }
    }
  }
  .transLate {
    background: $mainColor;
    color: #ffffff;
    display: inline-block;
    margin-left: 0.1rem;
    border-radius: 0.03rem;
    font-size: 12px;
    text-align: center;
    cursor: pointer;
    padding: 0.02rem 0.07rem;
  }
  .collect {
    cursor: pointer;
  }
  .el-icon-star-on {
    color: $color120;
    font-size: 0.34rem;
  }
}
div {
  padding: 0 0.4rem;
}
p {
  padding: 0 0.4rem;
}
.wrap {
  overflow: hidden;
  padding-top: 20px;
  border-top: 1px solid #ccc;
  position: relative;
  top: -20px;
  .left {
    float: left;
    width: 50%;
    height: auto;
  }
  .right {
    float: right;
    width: 50%;
    height: auto;
    background: #f4f5fa;
  }
  .mtitle {
    padding-top: 0.2rem;
    border: 0;
    text-align: center;
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 0.1rem;
  }
  .content {
    line-height: 2;
    color: #2c3e50;
  }
  .no-data {
    text-align: center;
  }
}
</style>
